<template>
  <v-container>
    <!-- 返回主页按钮 -->
    <v-row>
      <v-col cols="12">
        <v-btn color="primary" @click="$router.push('/')" class="mb-4">
          <v-icon start>mdi-home</v-icon>返回主页
        </v-btn>
        <v-text-field v-model="selectedDate" label="选择日期" type="date" @change="fetchRoomStatus" :min="minDate"
          prepend-inner-icon="mdi-calendar" dense outlined />
      </v-col>
    </v-row>
    <!-- 会议室状态卡片 -->
    <v-row>
      <v-col cols="12">
        <v-card>
          <v-card-title class="text-h5 d-flex align-center">
            <v-icon start>mdi-view-dashboard</v-icon>
            会议室状态
          </v-card-title>
          <v-card-text>
            <v-row v-if="!loading">
              <v-col v-for="room in meetingRooms" :key="room.id" cols="12" md="6" lg="4">
                <v-card :color="getRoomStatusColor(room)" variant="outlined" class="h-100">
                  <v-card-title class="text-h6">
                    <v-icon start>{{ getRoomIcon(room) }}</v-icon>
                    {{ room.roomName || '未命名会议室' }}
                  </v-card-title>
                  <v-card-text>
                    <div class="d-flex justify-space-between mb-2">
                      <span><strong>位置：</strong>{{ room.location || '未设置' }}</span>
                      <span><strong>容量：</strong>{{ room.capacity || '未知' }}人</span>
                    </div>
                    <div class="mb-2">
                      <strong>状态：</strong>
                      <v-chip :color="getStatusChipColor(room)" size="small" class="ml-2">
                        {{ getRoomStatusText(room) }}
                      </v-chip>
                    </div>
                    <div v-if="room.freeSlots && room.freeSlots.length > 0">
                      <strong>空闲时段：</strong>
                      <div class="mt-2">
                        <v-chip v-for="slot in room.freeSlots.slice(0, 3)"
                          :key="`free-${slot.date}-${slot.hour}-${slot.segment}`" color="success" variant="outlined"
                          size="small" class="ma-1">
                          {{ formatSlot(slot) }}
                        </v-chip>
                        <v-chip v-if="room.freeSlots.length > 3" color="info" variant="outlined" size="small"
                          class="ma-1">
                          +{{ room.freeSlots.length - 3 }}个
                        </v-chip>
                      </div>
                    </div>
                    <div v-if="room.occupiedSlots && room.occupiedSlots.length > 0">
                      <strong>占用时段：</strong>
                      <div class="mt-2">
                        <v-chip v-for="slot in room.occupiedSlots" :key="`${slot.date}-${slot.hour}-${slot.segment}`"
                          color="error" variant="outlined" size="small" class="ma-1">
                          {{ formatSlotRange(slot) }}
                        </v-chip>
                      </div>
                    </div>
                    <div
                      v-if="(!room.freeSlots || room.freeSlots.length === 0) && (!room.occupiedSlots || room.occupiedSlots.length === 0)"
                      class="text-grey">
                      <v-icon start>mdi-clock-off</v-icon>
                      当前时段无数据
                    </div>
                  </v-card-text>
                  <v-btn color="info" variant="text" @click="showSlotDetail(room)">
                    <v-icon start>mdi-eye</v-icon>查看详情
                  </v-btn>
                  <slot-detail-dialog v-model="dialogVisible" :room-name="selectedRoomName" :slots="selectedSlots"
                    @close="dialogVisible = false" />
                </v-card>

              </v-col>
            </v-row>
            <v-row v-if="loading">
              <v-col cols="12" class="text-center">
                <v-progress-circular indeterminate color="primary" size="64"></v-progress-circular>
                <div class="mt-4">正在加载会议室状态...</div>
              </v-col>
            </v-row>
            <v-row v-if="!loading && meetingRooms.length === 0">
              <v-col cols="12" class="text-center">
                <v-icon size="64" color="grey">mdi-office-building-off</v-icon>
                <div class="text-h6 mt-4">暂无会议室数据</div>
                <div class="text-body-2 text-grey">请联系管理员添加会议室</div>
              </v-col>
            </v-row>

          </v-card-text>
        </v-card>
      </v-col>
    </v-row>
    <!-- 统计信息卡片 -->
    <v-row class="mt-6">
      <v-col cols="12" md="4">
        <v-card color="primary" dark>
          <v-card-text class="text-center">
            <v-icon size="48">mdi-office-building</v-icon>
            <div class="text-h4 mt-2">{{ totalRooms }}</div>
            <div class="text-body-2">总会议室数</div>
          </v-card-text>
        </v-card>
      </v-col>
      <v-col cols="12" md="4">
        <v-card color="success" dark>
          <v-card-text class="text-center">
            <v-icon size="48">mdi-calendar-check</v-icon>
            <div class="text-h4 mt-2">{{ totalFreeSlots }}</div>
            <div class="text-body-2">空闲时段</div>
          </v-card-text>
        </v-card>
      </v-col>
      <v-col cols="12" md="4">
        <v-card color="error" dark>
          <v-card-text class="text-center">
            <v-icon size="48">mdi-calendar-remove</v-icon>
            <div class="text-h4 mt-2">{{ totalOccupiedSlots }}</div>
            <div class="text-body-2">占用时段</div>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>
    <!-- 错误提示 -->
    <v-snackbar v-model="showError" color="error">
      {{ errorMessage }}
      <template v-slot:actions>
        <v-btn color="white" text @click="showError = false">
          关闭
        </v-btn>
      </template>
    </v-snackbar>
  </v-container>
</template>

<script>
import api from '../services/api.js'
import SlotDetailDialog from './SlotDetailDialog.vue'
export default {
  name: 'RoomStatusPage',
  components: {
    SlotDetailDialog
  },
  data() {
    const today = new Date();
    const yyyy = today.getFullYear();
    const mm = String(today.getMonth() + 1).padStart(2, '0');
    const dd = String(today.getDate()).padStart(2, '0');
    return {

      loading: false,
      showError: false,
      errorMessage: '',
      meetingRooms: [],
      dialogVisible: false,
      selectedRoom: null,
      selectedSlots: [],
      selectedRoomName: '',

      selectedDate: `${yyyy}-${mm}-${dd}`,
      minDate: `${yyyy}-${mm}-${dd}`,

    }
  },
  computed: {
    totalRooms() {
      return this.meetingRooms.length
    },
    totalFreeSlots() {
      return this.meetingRooms.reduce((total, room) => total + (room.freeSlots ? room.freeSlots.length : 0), 0)
    },
    totalOccupiedSlots() {
      return this.meetingRooms.reduce((total, room) => total + (room.occupiedSlots ? room.occupiedSlots.length : 0), 0)
    }
  },
  methods: {
    async fetchRoomStatus() {
      try {
        this.loading = true
        // 获取所有会议室列表
        const roomsResponse = await api.get('/api/bookings/rooms')
        this.meetingRooms = roomsResponse.data || []
        console.log('获取到以下会议室数据', this.meetingRooms)
        // console.log(this.meetingRooms)
        // 为每个会议室获取空闲/占用时段
        for (const room of this.meetingRooms) {
          // 只查今天
          const today = new Date()
          const date = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`
          // 获取空闲时段
          const freeSlotsResponse = await api.get(`/api/bookings/room/${room.id}/free-slots?date=${date}`)
          room.freeSlots = freeSlotsResponse.data || []
          // 获取占用时段
          const occupiedSlotsResponse = await api.get(`/api/bookings/room/${room.id}/occupied-slots?date=${date}`)
          room.occupiedSlots = occupiedSlotsResponse.data || []
          console.log(`获取到会议室${room.id}数据`, room.freeSlots, room.occupiedSlots)
        }
        console.warn('已写入', this.meetingRooms)
      } catch (error) {
        console.log('获取会议室状态失败', error)
        this.showErrorMessage('获取会议室状态失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },
    getRoomStatusColor(room) {
      if (room.occupiedSlots && room.occupiedSlots.length > 0) return 'warning'
      if (room.freeSlots && room.freeSlots.length > 0) return 'success'
      return 'grey'
    },
    getRoomIcon(room) {
      if (room.occupiedSlots && room.occupiedSlots.length > 0) return 'mdi-clock'
      if (room.freeSlots && room.freeSlots.length > 0) return 'mdi-check-circle'
      return 'mdi-office-building'
    },
    getStatusChipColor(room) {
      if (room.occupiedSlots && room.occupiedSlots.length > 0) return 'warning'
      if (room.freeSlots && room.freeSlots.length > 0) return 'success'
      return 'grey'
    },
    getRoomStatusText(room) {
      if (room.occupiedSlots && room.occupiedSlots.length > 0) return '忙碌'
      if (room.freeSlots && room.freeSlots.length > 0) return '可用'
      return '未知'
    },
    formatSlot(slot) {
      const hour = slot.hour.toString().padStart(2, '0')
      const segment = slot.segment || slot.part || 1
      const minute = (segment - 1) * 10
      return `${hour}:${minute.toString().padStart(2, '0')}`
    },
    formatSlotRange(slot) {
      const hour = slot.hour.toString().padStart(2, '0')
      const segment = slot.segment || slot.part || 1
      const start = `${hour}:${((segment - 1) * 10).toString().padStart(2, '0')}`
      let endHour = slot.hour
      let endMinute = segment * 10
      if (endMinute >= 60) {
        endHour += Math.floor(endMinute / 60)
        endMinute = endMinute % 60
      }
      const end = `${endHour.toString().padStart(2, '0')}:${endMinute.toString().padStart(2, '0')}`
      return `${start}-${end}`
    },
    showErrorMessage(message) {
      this.errorMessage = message
      this.showError = true
    },
    showSlotDetail(room) {
      // 合并空闲和占用slot，按时间排序
      const allSlots = [
        ...(room.freeSlots || []).map(slot => ({ ...slot, occupied: false })),
        ...(room.occupiedSlots || []).map(slot => ({ ...slot, occupied: true }))
      ].sort((a, b) => a.hour * 10 + a.segment - (b.hour * 10 + b.segment))
      this.selectedRoom = room
      this.selectedSlots = allSlots
      this.selectedRoomName = room.roomName || '未命名会议室'
      this.dialogVisible = true
    },
  },
  mounted() {
    this.fetchRoomStatus()
  }
}
</script>

<style scoped>
.h-100 {
  height: 100%;
}
</style>